﻿using ApplicationGUI.Properties;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Metabase;
using ApplicationGUI.ChildForms;
using Metabase.MetabaseObjects;

namespace ApplicationGUI
{
    public partial class MainForm : Form
    {
        public MetabaseHandler metabaseHandler;
        public MainForm()
        {
            InitializeComponent();
        }

        // Процедура восстанавливает параметры окна
        private void loadWindowState()
        {
            this.WindowState = Settings.Default.MainWindowState;
            if (this.WindowState != FormWindowState.Maximized)
            {
                this.Location = Settings.Default.MainWindowLocation;
                this.Size = Settings.Default.MainWindowSize;
            }
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            // Загрузим параметры окна
            loadWindowState();
            // Выполним подключение к репозиторию
            Application.DoEvents();
            Cursor.Current = Cursors.WaitCursor;
            bool connResult = metabaseHandler.dbHandler.Connect();
            if (!connResult)
            {
                MessageBox.Show(metabaseHandler.dbHandler.connectException.Message, AppResources.ErrorHeader, MessageBoxButtons.OK, MessageBoxIcon.Error);
                //Close();
            }
            else
            {
                // Откроем дочернее окно со структурой репозитория
                showMetabaseWindow();
            }
            Cursor.Current = Cursors.Default;
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            Settings.Default.MainWindowState = this.WindowState;
            if (this.WindowState != FormWindowState.Maximized)
            {
                Settings.Default.MainWindowLocation = this.Location;
                Settings.Default.MainWindowSize = this.Size;
            }
            Settings.Default.Save();
        }

        private void showMetabaseWindow()
        {
            MetabaseForm metabaseForm = new MetabaseForm();
            metabaseForm.MdiParent = this;
            metabaseForm.WindowState = FormWindowState.Maximized;
            metabaseForm.metabaseHandler = metabaseHandler;
            metabaseForm.InitMetabase();
            metabaseForm.Show();
        }
        
        private void connectToolStripMenuItem_Click(object sender, EventArgs e)
        {
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Close();
        }

        // Процедура для отрисовки процесса ожидания при длительных операциях
        private void beginOperation(string infoText)
        {
            StatusLabel.Text = infoText;
            Application.DoEvents();
            Cursor.Current = Cursors.WaitCursor;
        }

        // Процедура перевода приложения в исходное состояние
        private void endOperation()
        {
            Cursor.Current = Cursors.Default;
            StatusLabel.Text = "";
        }

        private void connectToRepositoryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ConnectToRepository();
        }

        // Процедура закрытия текущего репозитрия и открытия нового
        private void ConnectToRepository()
        {
            Form activeChild = this.ActiveMdiChild;
            if (activeChild != null)
            {
                activeChild.Close();
            }
            Cursor.Current = Cursors.WaitCursor;
            // Выполним попытку подключениея к репозиторию
            metabaseHandler = MetabaseConnector.ConnectionToMetabase();
            if (metabaseHandler != null)
            {
                // Если все успешно, то покажем окно нового репозитория
                showMetabaseWindow();
            }
            Cursor.Current = Cursors.Default;
        }

        private void dictionaryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            EditDictionaryForm Form = new EditDictionaryForm();
            Form.ShowDialog();
        }
        
        private void deleteSelectedItemToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Form activeChild = this.ActiveMdiChild;
            if (activeChild == null) return;
            MetabaseObject selectedObject = (activeChild as MetabaseForm).selectedObject;
            TreeNode selectedNode = (activeChild as MetabaseForm).selectedNode;
            MetabaseOperations.DeleteObjectItem(metabaseHandler, selectedObject, selectedNode);
        }

        private void refreshStructureToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Form activeChild = this.ActiveMdiChild;
            if (activeChild == null) return;
            (activeChild as MetabaseForm).InitMetabase();
        }

        private void createFolderToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Form activeChild = this.ActiveMdiChild;
            if (activeChild == null) return;
            TreeNode newNode = (activeChild as MetabaseForm).selectedNode.Nodes.Add(AppResources.NewFolderName);
            newNode.Parent.Expand();
            newNode.ImageIndex = (int)ObjectTypes.otFolder;
            newNode.SelectedImageIndex = (int)ObjectTypes.otFolder;
            newNode.TreeView.SelectedNode = newNode;
            newNode.BeginEdit();
        }
    }
}
